package com.bawei.module_mine.ui

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityAddAddressBinding
import com.bawei.module_mine.model.entity.CityEntity
import com.bawei.module_mine.model.entity.DistrictEntity
import com.bawei.module_mine.model.entity.ProvinceEntity
import com.bawei.module_mine.model.service.AddressRegionService
import com.bawei.module_mine.state.AddAddressState
import com.bawei.module_mine.viewmodel.AddAddressViewModel
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import kotlinx.coroutines.launch

@Route(path = "/module_mine/AddAddressActivity")
class AddAddressActivity : BaseMVIActivity() {
    private lateinit var binding: ActivityAddAddressBinding
    private lateinit var viewModel: AddAddressViewModel

    private var selectedProvince: ProvinceEntity? = null
    private var selectedCity: CityEntity? = null
    private var selectedDistrict: DistrictEntity? = null
    private var selectedTag: String? = "家"

    private var regionPicker: OptionsPickerView<String>? = null

    companion object {
        private var cachedProvinces: List<ProvinceEntity>? = null
        private var cachedCityMap: Map<String, List<CityEntity>>? = null
        private var cachedDistrictMap: Map<String, List<DistrictEntity>>? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddAddressBinding.inflate(layoutInflater)
        setContentView(binding.root)
        generateViewModel()
        initUI()
    }

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[AddAddressViewModel::class.java]
    }

    private fun initUI() {
        binding.ivBack.setOnClickListener { finish() }
        // 标签选择
        val tagViews = listOf(binding.tvTagHome, binding.tvTagCompany, binding.tvTagSchool)
        tagViews.forEach { tv ->
            tv.setOnClickListener {
                tagViews.forEach { it.isSelected = false; it.setBackgroundResource(R.drawable.bg_tag_type) }
                tv.isSelected = true
                tv.setBackgroundResource(R.drawable.bg_tag_default)
                selectedTag = tv.text.toString()
            }
        }
        // 默认选中"家"
        binding.tvTagHome.isSelected = true
        binding.tvTagHome.setBackgroundResource(R.drawable.bg_tag_default)

        // 省市区选择
        binding.layoutRegion.setOnClickListener {
            showRegionPicker()
        }

        // 保存按钮
        binding.btnSave.setOnClickListener {
            val name = binding.etName.text.toString().trim()
            val phone = binding.etPhone.text.toString().trim()
            val address = binding.etAddress.text.toString().trim()
            val province = selectedProvince?.provinceName ?: ""
            val provinceCode = selectedProvince?.provinceCode ?: ""
            val city = selectedCity?.cityName ?: ""
            val cityCode = selectedCity?.cityCode ?: ""
            val district = selectedDistrict?.districtName ?: ""
            val districtCode = selectedDistrict?.districtCode ?: ""
            val tag = selectedTag
            val isDefault = binding.switchDefault.isChecked

            // 表单校验
            if (name.isEmpty()) {
                showToast("请输入收货人")
                return@setOnClickListener
            }
            if (name.length > 15) {
                showToast("收货人最多15个字")
                return@setOnClickListener
            }
            if (phone.length != 11 || !phone.all { it.isDigit() }) {
                showToast("请输入11位手机号")
                return@setOnClickListener
            }
            if (province.isEmpty() || city.isEmpty() || district.isEmpty()) {
                showToast("请选择地区")
                return@setOnClickListener
            }
            if (address.isEmpty()) {
                showToast("请输入详细地址")
                return@setOnClickListener
            }
            if (address.length > 50) {
                showToast("详细地址最多50个字")
                return@setOnClickListener
            }
            lifecycleScope.launch {
                if (isDefault) {
                    // 先拉取所有地址，将所有 isDefault==1 的设为0
                    val service = com.bawei.module_mine.model.service.AddressService()
                    val all = service.getAddressList().data ?: emptyList()
                    all.filter { it.isDefault == 1 }.forEach { addr ->
                        service.updateAddress(addressToApiMap(addr, false))
                    }
                }
                viewModel.intents.send(
                    com.bawei.module_mine.intent.AddAddressIntent.SaveAddress(
                        name, phone, province, provinceCode, city, cityCode, district, districtCode, address, tag, isDefault
                    )
                )
            }
        }
    }

    private suspend fun loadRegionData(): Triple<List<ProvinceEntity>, Map<String, List<CityEntity>>, Map<String, List<DistrictEntity>>> {
        if (cachedProvinces != null && cachedCityMap != null && cachedDistrictMap != null) {
            return Triple(cachedProvinces!!, cachedCityMap!!, cachedDistrictMap!!)
        }
        val service = AddressRegionService()
        val provinces = service.getProvinces().data ?: emptyList()
        val cityMap = mutableMapOf<String, List<CityEntity>>()
        for (province in provinces) {
            val cities = service.getCities(province.provinceCode).data ?: emptyList()
            cityMap[province.provinceCode] = cities
        }
        val districtMap = mutableMapOf<String, List<DistrictEntity>>()
        for (cities in cityMap.values) {
            for (city in cities) {
                val districts = service.getDistricts(city.cityCode).data ?: emptyList()
                districtMap[city.cityCode] = districts
            }
        }
        cachedProvinces = provinces
        cachedCityMap = cityMap
        cachedDistrictMap = districtMap
        return Triple(provinces, cityMap, districtMap)
    }

    private fun showRegionPicker() {
        lifecycleScope.launch {
            val (provinces, cityMap, districtMap) = loadRegionData()
            val options1Items = provinces.map { it.provinceName }.ifEmpty { listOf("无省份") }
            val options2Items = provinces.map { province ->
                val cities = cityMap[province.provinceCode]
                if (cities.isNullOrEmpty()) listOf("无城市") else cities.map { it.cityName }
            }.ifEmpty { listOf(listOf("无城市")) }
            val options3Items = provinces.map { province ->
                val cities = cityMap[province.provinceCode]
                if (cities.isNullOrEmpty()) {
                    listOf(listOf("无区县"))
                } else {
                    cities.map { city ->
                        val districts = districtMap[city.cityCode]
                        if (districts.isNullOrEmpty()) listOf("无区县") else districts.map { it.districtName }
                    }
                }
            }.ifEmpty { listOf(listOf(listOf("无区县"))) }
            regionPicker = OptionsPickerBuilder(this@AddAddressActivity, OnOptionsSelectListener { options1, options2, options3, _ ->
                val provinceName = options1Items.getOrNull(options1) ?: "无省份"
                val cityName = options2Items.getOrNull(options1)?.getOrNull(options2) ?: "无城市"
                val districtName = options3Items.getOrNull(options1)?.getOrNull(options2)?.getOrNull(options3) ?: "无区县"
                selectedProvince = provinces.getOrNull(options1)
                selectedCity = cityMap[selectedProvince?.provinceCode]?.getOrNull(options2)
                selectedDistrict = districtMap[selectedCity?.cityCode]?.find { it.districtName == districtName }
                val regionText = "$provinceName $cityName $districtName"
                binding.tvRegion.text = regionText
                binding.tvRegion.setTextColor(0xFF222222.toInt())
            })
                .setTitleText("选择省市区")
                .setSubmitText("确定")
                .setCancelText("取消")
                .setOutSideCancelable(true)
                .setLineSpacingMultiplier(2.2f)
                .build()
            regionPicker?.setPicker(options1Items, options2Items, options3Items)
            regionPicker?.show()
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    when (state) {
                        is AddAddressState.Init -> {}
                        is AddAddressState.Loading -> {
                            binding.btnSave.isEnabled = false
                        }
                        is AddAddressState.Success -> {
                            binding.btnSave.isEnabled = true
                            showToast("保存成功")
                            setResult(RESULT_OK)
                            finish()
                        }
                        is AddAddressState.Failed -> {
                            binding.btnSave.isEnabled = true
                            showToast(state.msg)
                        }
                    }
                }
            }
        }
    }

    override fun getLayoutRootView(): View {
        if (!::binding.isInitialized) {
            binding = ActivityAddAddressBinding.inflate(layoutInflater)
        }
        return binding.root
    }

    private fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    private fun addressToApiMap(addr: com.bawei.module_mine.model.entity.AddressEntity, isDefault: Boolean): Map<String, Any?> {
        return mapOf(
            "id" to addr.id,
            "address" to (addr.address ?: ""),
            "checked" to isDefault,
            "cityCode" to (addr.cityCode ?: ""),
            "cityName" to (addr.cityName ?: ""),
            "default" to isDefault,
            "districtCode" to (addr.districtCode ?: ""),
            "districtName" to (addr.districtName ?: ""),
            "partnerId" to "",
            "postalCode" to (addr.postCode ?: ""),
            "provinceCode" to (addr.provinceCode ?: ""),
            "provinceName" to (addr.provinceName ?: ""),
            "receiverAddress" to (addr.address ?: ""),
            "receiverName" to (addr.receiverName ?: ""),
            "receiverPhone" to (addr.receiverPhone ?: "")
        )
    }
} 